package servlet;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import decoder.ChineseDecoder;
import factory.DaoFactory;

import bean.OrderListBean;

import model.Goods;
import model.Member;
import model.Order;
import model.Record;

/**
 * Servlet implementation class OrderListServlet
 */
@WebServlet("/OrderListServlet")
public class OrderListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public OrderListServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("deprecation")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name = ChineseDecoder.getUtf8FromIso8859_1(request.getParameter("name"));
		List<Order> list = DaoFactory.getOrderDao().findByCustomer(name);
		Date today = new Date(Calendar.getInstance().getTimeInMillis());
		for (int i = 0; i < list.size(); i++) {
			Order order = list.get(i);
			Date date = order.getDate();
			if (today.getYear() != date.getYear() || today.getMonth() != date.getMonth() || today.getDate() != date.getDate()) {
				list.remove(i);
				DaoFactory.getOrderDao().removeById(order.getId());
			}
		}
		OrderListBean bean = new OrderListBean(list);
		request.setAttribute("orderList", bean);
		String address ="/jsp/OrderList.jsp?name=" + name;
		RequestDispatcher dispatcher =request.getRequestDispatcher(address);
		dispatcher.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		boolean success = true;
		String name = ChineseDecoder.getUtf8FromIso8859_1(request.getParameter("name"));
		List<Order> list = DaoFactory.getOrderDao().findByCustomer(name);
		for (int i = 0; i < list.size(); i++) {
			Order order = list.get(i);
			Timestamp time = new Timestamp(Calendar.getInstance().getTimeInMillis());
			Record record = new Record(null, name, time, order.getGoodsId(), order.getGoodsName(), order.getQuantity(), order.getPrice());

			Member member = DaoFactory.getMemberDao().find(name);
			if (order.getPrice() > member.getBalance()) {
				response.sendRedirect(request.getContextPath() + "/jsp/ErrorPage.jsp?error=OrderBalanceError&name=" + name + "&id=" + order.getGoodsId() + "&date=" + order.getDate());
				return;
			}

			Goods goods = DaoFactory.getGoodsDao().find(order.getGoodsId(), order.getDate());
			goods.setQuantity(goods.getQuantity() - order.getQuantity());
			member.setBalance(member.getBalance() - order.getPrice());
			member.setTotalConsumption(member.getTotalConsumption() + order.getPrice());
			success = success && DaoFactory.getRecordDao().save(record) && DaoFactory.getGoodsDao().updateQuantityByIdDate(goods) && DaoFactory.getMemberDao().updateBalanceByName(member) && DaoFactory.getMemberDao().updateConsumptionByName(member) && DaoFactory.getOrderDao().removeById(order.getId());
		}
		
		if (success) {
			response.sendRedirect(request.getContextPath() + "/ConsumptionRecordServlet?name=" + name);
		} else {
			response.sendRedirect(request.getContextPath() + "/jsp/ErrorPage.jsp?error=PayDatabaseError&name=" + name);
		}
	}

}
